#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
from modules.connect_db import engine, UserProfile, RemoteUser, Host, Group, AuditLog, \
    BindHost, AuditLog, Admin_user, Group_with_UserProfile, BindHost_with_Group
from sqlalchemy.orm import sessionmaker
session_connet = sessionmaker(bind=engine)
session = session_connet()


class Admin_run(object):
    def __init__(self, user):
        self.user = user

    def menu(self):
        choise_menu = '''
                   \033[1;31m
                      ---------Welcome  %s----------
                      1. 添加用户
                      2. 添加主机
                      3. 添加主机组
                      4. 添加主机认证账户
                      5. 绑定主机认证账户
                      6. 绑定用户到主机组
                      7. 绑定主机到主机组
                      8. 查询操作日志
                      9. 退出
                   \033[0m

                   ''' % self.user

        menu_dict = {
            '1': Admin_run.add_userprofile,
            '2': Admin_run.add_host,
            '3': Admin_run.add_hostgroup,
            '4': Admin_run.add_remoteuser,
            '5': Admin_run.host_with_remoteuser,
            '6': Admin_run.group_with_userprofile,
            '7': Admin_run.group_with_host,
            '8': Admin_run.select_user_cmd,
            '9': 'exit'
        }

        while True:
            print(choise_menu)
            choise = input('请选择>>>')
            if choise in menu_dict:
                if choise == '9':
                    exit()
                else:
                    menu_dict[choise](self)
            else:
                print('输入错误！')

    def add_userprofile(self):
        username = input('请输入用户名>>>')
        password = input('请输入密码>>>')
        obj = session.query(UserProfile).filter(UserProfile.username == username,
                                                UserProfile.password == password).first()
        if obj is None:  # 查询需要添加账户是否存在，不存在则允许添加
            user_add = UserProfile(username=username,
                                   password=password)
            session.add(user_add)
            session.commit()
            print('添加成功！')
        else:
            print('用户已存在')

    def add_host(self):
        hostname = input('请输入主机名>>>')
        ip_addr = input('请输入主机IP地址>>>')
        port = input('请输入端口>>>')
        obj = session.query(Host).filter(Host.hostname == hostname,
                                         Host.ip_addr == ip_addr,
                                         Host.port == port).first()
        if obj is None:  # 查询主机是否存在，不存在则允许添加
            host_add = Host(hostname=hostname,
                            ip_addr=ip_addr,
                            port=port)
            session.add(host_add)
            session.commit()
            print('添加成功！')
        else:
            print('主机已存在！')

    def add_hostgroup(self):
        group_name = input('请输入主机组名>>>')
        obj = session.query(Group).filter(Group.name == group_name).first()
        if obj is None:    # 查询主机组是否存在，不存在则允许添加
            group_add = Group(name=group_name)
            session.add(group_add)
            session.commit()
            print('添加成功！')
        else:
            print('主机组已存在！')

    def add_remoteuser(self):
        username = input('请输入远程登录账户>>>')
        password = input('请输入密码>>>')
        obj = session.query(RemoteUser).filter(RemoteUser.username == username,
                                               RemoteUser.password == password).first()
        if obj is None:    # 查询远程验证主机账户是否存在，不存在则允许添加
            remoteuser_add = RemoteUser(username=username,
                                        password=password)
            session.add(remoteuser_add)
            session.commit()
            print('添加成功！')
        else:
            print('远程登录账户已存在！')

    def host_with_remoteuser(self):
        host_list = session.query(Host).all()  # 查询主机列表
        for index, i in enumerate(host_list):
            print(index, i.hostname, i.ip_addr)
        host_choise = input('请选择主机>>>')
        if host_choise.isdigit():
            if host_list[int(host_choise)]:
                host_id = host_list[int(host_choise)].id
        remoteuser_list = session.query(RemoteUser).all()  # 查询远程主机验证账户列表
        for index, i in enumerate(remoteuser_list):
            print(index, i.username, i.password)
        remoteuser_choise = input('请选择远程账户>>>')
        if remoteuser_choise.isdigit():
            if remoteuser_list[int(remoteuser_choise)]:
                remoteuser_id = remoteuser_list[int(remoteuser_choise)].id
        obj = session.query(BindHost).filter(BindHost.host_id == host_id,
                                             BindHost.remoteuser_id == remoteuser_id).first()
        if obj is None:  # 查询是否存在，不存在则允许创建
            bindhots = BindHost(host_id=host_id,
                                remoteuser_id=remoteuser_id)
            session.add(bindhots)
            session.commit()
            print('绑定成功!')
        else:
            print('主机已绑定远程账户')

    def group_with_userprofile(self):
        user_list = session.query(UserProfile).all()  # 查找已存在的主机
        for index, i in enumerate(user_list):
            print(index,i.username)
        user_choise = input('请选择用户>>>')
        if user_choise.isdigit():
            if user_list[int(user_choise)]:
                user = user_list[int(user_choise)]
                group_list = session.query(Group).all()  # 查找已存在的主机组
                for index, i in enumerate(group_list):
                    print(index,i.name)
                group_choise = input('请选择主机组>>>')
                if group_choise.isdigit():
                    if group_list[int(group_choise)]:
                        group = group_list[int(group_choise)]
                        obj = session.query(Group_with_UserProfile).filter(Group_with_UserProfile.userprofile_id ==
                                                                           user.id,
                                                                           Group_with_UserProfile.group_id ==
                                                                           group.id).first()
                        if obj is None: # 查询是否存在，不存在则创建
                            group.user_profiles.append(user)
                            session.commit()
                            print('绑定成功！')
                        else:
                            print('该用户已绑定该主机组')

    def group_with_host(self):
        bindhost_list = session.query(BindHost).all()  # 查询已存在的绑定主机
        for index, i in enumerate(bindhost_list):
            print(index, i.host.ip_addr, i.remoteuser.username)
        host_choise = input('请选择主机>>>')
        if host_choise.isdigit():
            if bindhost_list[int(host_choise)]:
                bindhost = bindhost_list[int(host_choise)]
                group_list = session.query(Group).all()  # 查询已存在的主机组
                for index, i in enumerate(group_list):
                    print(index, i.name)
                group_choise = input('请选择主机组>>>')
                if group_choise.isdigit():
                    if group_list[int(group_choise)]:
                        group = group_list[int(group_choise)]
                        obj = session.query(BindHost_with_Group).\
                            filter(BindHost_with_Group.bindhost_id == bindhost.id,
                                   BindHost_with_Group.group_id == group.id).first()
                        if obj is None:  # 查询是否存在，不存在则创建
                            bindhost.groups.append(group)
                            session.commit()
                            print('绑定成功！')
                        else:
                            print('该主机已绑定主机组！')

    def select_user_cmd(self):
        group_list = session.query(Group).all()  # 查询已存在的主机组
        for index, i in enumerate(group_list):
            print(index, i.name)
        group_choise = input('请选择主机组>>>')
        if group_choise.isdigit():
            if group_list[int(group_choise)]:
                group_id = group_list[int(group_choise)].id
                user_list = session.query(Group_with_UserProfile).\
                    filter(Group_with_UserProfile.group_id == group_id).all()  # 查询选择的主机组绑定的用户
                for index, x in enumerate(user_list):
                    user_name = session.query(UserProfile).\
                        filter(UserProfile.id == x.userprofile_id).first()
                    print(index, user_name.username)  # 查询用户名

                user_choise = input('请选择用户>>>')
                if user_choise.isdigit():
                    if user_list[int(user_choise)]:
                        user_id = user_list[int(user_choise)].userprofile_id
                        host_list = session.query(BindHost_with_Group).\
                            filter(BindHost_with_Group.group_id == group_id).all()  # 查询绑定的主机
                        for index, f in enumerate(host_list):
                            host_name = session.query(BindHost).\
                                filter(BindHost.id == f.bindhost_id).first()
                            print(index, host_name.host.ip_addr, host_name.remoteuser.username)  # 查询主机详细信息
                        host_choise = input('请选择主机>>>')
                        if host_choise.isdigit():
                            if host_list[int(host_choise)]:
                                bindhost_id = host_list[int(host_choise)].bindhost_id
                                cmd_list = session.query(AuditLog).\
                                    filter(AuditLog.user_id == user_id,
                                           AuditLog.bind_host_id == bindhost_id). \
                                    order_by(AuditLog.date.desc()).all()  # 根据用户id和绑定主机id按时间倒序排列
                                for i in cmd_list:
                                    print(i.date, i.user_profile.username, i.cmd)



